// AWTDialogPeer.cpp : implementation file
//

#include "stdafx.h"
#include "AWTDialogPeer.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// AWTDialogPeer

IMPLEMENT_DYNAMIC(AWTDialogPeer, CWnd)

AWTDialogPeer::AWTDialogPeer(AWTComponent* comp)
{
	m_comp = comp;
}

AWTDialogPeer::~AWTDialogPeer()
{
	if (m_hWnd != NULL)
		DestroyWindow();
}


BEGIN_MESSAGE_MAP(AWTDialogPeer, CWnd)
	//{{AFX_MSG_MAP(AWTDialogPeer)
	ON_WM_ERASEBKGND()
	ON_WM_SYSCOMMAND()
	ON_MESSAGE(WM_AWTKEYEVENT, OnAWTKeyEvent)
	ON_MESSAGE(WM_AWTFOCUSEVENT, OnAWTFocusEvent)
	ON_WM_SETFOCUS()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// AWTDialogPeer message handlers


BOOL AWTDialogPeer::OnEraseBkgnd(CDC* pDC) 
{
	m_comp->eraseBackground(pDC);
	return TRUE;
/*
	CBrush* br = m_comp->getBkBrush();
	if (br != NULL)
	{
//		::UnrealizeObject((HBRUSH)*br);
		CBrush* brOld = pDC->SelectObject(br);
		CRect rc;
		GetClientRect(&rc);
		pDC->FillRect(&rc, br);
		pDC->SelectObject(brOld);
		return TRUE;
	}
	else
	{
		return CWnd::OnEraseBkgnd(pDC);
	}
*/
}

void AWTDialogPeer::OnSysCommand(UINT nID, LPARAM lParam) 
{
	if (nID	== SC_CLOSE)
	{
		AWTDialog* dlg = (AWTDialog*)m_comp;
		if (dlg->isModal())
		{
			EndModalLoop(IDCANCEL);
		}
		else
		{
			AWTWindowEvent e(m_comp, AWTWindowEvent::WINDOW_CLOSING);
			dlg->processWindowEvent(&e);
		}
		return;
	}
	
	CWnd::OnSysCommand(nID, lParam);
}

long AWTDialogPeer::OnAWTKeyEvent(WPARAM wp, LPARAM lp) 
{
	AWTDialog* dlg = (AWTDialog*)m_comp;
	AWTKeyEvent* e = (AWTKeyEvent*)lp;
	switch (e->getId())
	{
		case AWTKeyEvent::KEY_PRESSED:
			if ((e->getKeyChar() == VK_TAB) && ((AWTComponent*)e->getSource())->isFocusTraversable())
			{
				AWTFocusManager* fm = dlg->getFocusManager();
				if (::GetKeyState(VK_SHIFT) < 0)  //SHIFT is pressed
					fm->focusPrevious((AWTComponent*)e->getSource());
				else
					fm->focusNext((AWTComponent*)e->getSource());
			}
			break;
	}

	return 0;
}

long AWTDialogPeer::OnAWTFocusEvent(WPARAM wp, LPARAM lp) 
{
	AWTDialog* dlg = (AWTDialog*)m_comp;
	AWTFocusEvent* e = (AWTFocusEvent*)lp;
	AWTFocusManager* fm;
	switch (e->getId())
	{
		case AWTFocusEvent::FOCUS_GAINED:
			fm = dlg->getFocusManager();
			fm->setFocusOwner((AWTComponent*)e->getSource());
			break;
/*
		case AWTFocusEvent::FOCUS_LOST:
			fm = dlg->getFocusManager();
			AWTComponent* c = (AWTComponent*)e->getSource();
			if (fm->getFocusOwner() == c)
				fm->setFocusOwner(NULL);
			break;
*/
	}

	return 0;
}


void AWTDialogPeer::OnSetFocus(CWnd* pOldWnd) 
{
	CWnd::OnSetFocus(pOldWnd);
	AWTDialog* dlg = (AWTDialog*)m_comp;
	dlg->getFocusManager()->activateFocus();
}
